package com.anjingsi.tools.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CacheUtil {
    private static CacheUtil instance;
    private Map<String, Object> hashMap;

    private CacheUtil() {
        this.hashMap = new ConcurrentHashMap<>();
    }

    public static synchronized CacheUtil GetInstance() {
        if (instance == null) {
            instance = new CacheUtil();
        }
        return instance;
    }

    public static CacheUtil GetOrCreate(String key) {
        CacheUtil cacheUtil = (CacheUtil) CacheUtil.GetInstance().get(key);
        if (cacheUtil == null) {
            cacheUtil = CacheUtil.Create(key);
        }
        return cacheUtil;
    }

    private static synchronized CacheUtil Create(String key) {
        CacheUtil cacheUtil = (CacheUtil) CacheUtil.GetInstance().get(key);
        if (cacheUtil == null) {
            cacheUtil = new CacheUtil();
            CacheUtil.GetInstance().set(key, cacheUtil);
        }
        return cacheUtil;
    }

    public Map<String, Object> get() {
        return this.hashMap;
    }

    public void set(String key, Object value) {
        this.hashMap.put(key, value);
    }

    public Object get(String key) {
        Long cacheHoldTime = (Long) this.hashMap.get(key + "_HoldTime");
        if(cacheHoldTime == null){
            return this.hashMap.get(key);
        }
        if (cacheHoldTime < System.currentTimeMillis()) {
            remove(key);
            return null;
        }
        return this.hashMap.get(key);
    }

    public boolean containsKey(String key) {
        return this.hashMap.containsKey(key);
    }

    public void remove(String key) {
        this.hashMap.remove(key);
    }

    public void clear() {
        this.hashMap.clear();
    }

    public void setExpiration(String key, int second){
        this.hashMap.put(key + "_HoldTime", System.currentTimeMillis() + second * 1000);//缓存失效时间
    }
}
